<template>
  <div class="commonMenu-wrapper">
    <a-button @click="handleBack" size="mini" v-if="operateText">{{
      operateText
    }}</a-button>
    <a-tabs
      v-show="menuShow"
      :class="{
        marginBottom: marginBottom,
      }"
      v-model:activeKey="activeIndex"
      @tab-click="handleChangeTab"
    >
      <template v-for="item in treeMenus">
        <a-tab-pane
          v-if="!item.hide"
          :disabled="item.disabled"
          :key="item.compPath"
          :name="item.compPath"
          :tab="item.label"
        >
        </a-tab-pane>
      </template>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, watchEffect } from "vue";

const activeIndex = ref("");
const menuShow = ref<boolean>(false);
const treeMenus = ref<any[]>([]);
const props = defineProps({
  operateText: {
    default: "返回",
    type: String,
  },
  marginBottom: {
    default: true,
    type: Boolean,
  },
  menuList: {
    type: Array,
    default: null,
  },
  clickJumpable: {
    default: true,
    type: Boolean,
  },
  alwaysShow: {
    default: false,
    type: Boolean,
  },
  value: {
    type: String,
    default: "",
  },
});
const emits = defineEmits(["input", "handleChange"]);
const refreshMenu = () => {
  const path = window.location.pathname;
  menuShow.value = props.alwaysShow;
  let activeMenu = treeMenus.value.find((item) => {
    if (item.compName) {
      const pathReg = new RegExp(`${item.compName}$`);
      if (pathReg.test(path)) {
        return true;
      }
    }
    return false;
  });
  if (activeMenu) {
    activeIndex.value = activeMenu.compPath;
    menuShow.value = true;
  }
};

const handleBack = () => {
  window.history.go(-1);
};

const handleChangeTab = (path: any) => {
  emits("input", path);
  emits("handleChange", path);
  if (props.clickJumpable) {
    window.history.pushState({}, '', path);
  }
};
watch(() => window.location.pathname, refreshMenu, {
  deep: true,
  immediate: true,
});
watchEffect(() => {
  activeIndex.value = props.value;
});
watchEffect(() => {
  treeMenus.value = props.menuList;
  refreshMenu();
});
</script>

<style scoped lang="scss">
.commonMenu-wrapper {
  display: flex;
  align-items: center;
  > button {
    margin-right: 8px;
  }
  > .ant-tabs {
    flex: 1;
  }
}
.marginBottom {
  margin-bottom: 12px;

  ::v-deep.el-tabs__header {
    margin-bottom: 15px;
  }
}

::v-deep .el-tabs__header {
  margin-bottom: 0px;
}
</style>
